package com.fs.base.vo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import lombok.Data;
import lombok.NoArgsConstructor;

import org.springframework.data.domain.Page;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.BeforeFilter;

/**
 * @author TiddlerCJ
 */
@Data
@NoArgsConstructor
public class DataGrid {
	/**
	 * 是否树形表格
	 */
	private Boolean  isTreeGrid = false;
	/**
	 *树形子关系字段
	 */
	private String treeId;
	/**
	 *树形父关系字段
	 */
	private String treePid;
	/**
	 * 总记录
	 */
	private Long total = 0l ;
	/**
	 * 单页数据集
	 */
	private List<?> rows;
	/**
	 * 当前实体类名（预留使用）
	 */
	private String className;
	
	public DataGrid (Long total,List<?> rows){
		this.total = total;
		this.rows = rows;
	}
	
	/**
	 * 适配分页grid
	 * @param page
	 * @return
	 */
	public static <K>  DataGrid gridBuilder(Page<K> page){
		return new DataGrid(page.getTotalElements(),  page.getContent());
	}
	/**
	 * 适配一般集合
	 * @param rows
	 * @return
	 */
	public static <K> DataGrid gridBuilder(List<K> rows){
		Long len =  Long.parseLong(rows.size() + "" );
		return new DataGrid(len,  rows); 
	}
	
	/**
	 * 树形格式化1
	 * @param rows
	 * @param grid
	 * @return
	 */
	public static <K> DataGrid treeBuilder(List<K> rows,DataGrid grid){
		return treeBuilder(rows, grid.getTreeId(),grid.getTreePid());
	}
	
	/**
	 * 树形格式化2
	 * @param rows
	 * @param treeId 树形主键字段
	 * @param treePid 树形主键对应的父亲节点字段
	 * @return
	 */
	public static <K> DataGrid treeBuilder(List<K> rows,String treeId,String treePid){
		List<Tree> treeList = new ArrayList<Tree>();
		List<JSONObject> jsonList = new ArrayList<JSONObject>();
		String json = JSON.toJSONString(rows);
		JSONArray array = JSON.parseArray(json);
		String treeIdValue = null ,treePidValue = null;
		for(int i=0,len=array.size();i<len;i++){
			JSONObject item = array.getJSONObject(i);
			treeIdValue = item.getString(treeId);
			treePidValue = item.getString(treePid)==null? "" : item.getString(treePid);
			Tree tree = new Tree(treeIdValue, treePidValue, item);
			treeList.add(tree);
		}
		List<Tree> nodeList = new ArrayList<Tree>();
		for(Tree node1 : treeList){  
		    boolean mark = false;  
		    for(Tree node2 : treeList){  
		        if(node1.getTreePid()!=null && node1.getTreePid().equals(node2.getTreeId())){  
		            mark = true;  
		            if(node2.getChildren() == null)  
		                node2.setChildren(new ArrayList<Tree>());  
		            node2.getChildren().add(node1);   
		            break;  
		        }  
		    }  
		    if(!mark){  
		        nodeList.add(node1);   
		    }  
		}  
		BeforeFilter treeFilter = new BeforeFilter () {
			@SuppressWarnings("unchecked")
			public void writeBefore(Object object) {
				String key = "o";
				JSONObject json = (JSONObject) JSON.toJSON(object);
				if(json.containsKey(key)){
					JSONObject self = json.getJSONObject(key);
					Map<String,Object> map = JSONObject.toJavaObject(self, Map.class);
					for(String m: map.keySet()){
						writeKeyValue(m, map.get(m));
					}
				}
			}
		};
		String tempJson = null;
		for(Tree tree: nodeList){
			tempJson =  JSONObject.toJSONString(tree, treeFilter);
			JSONObject tt = JSON.parseObject(tempJson);
			jsonList.add(tt);
		}
		return gridBuilder(jsonList);
	}
}
